<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\Department;
use App\Model\Party;
use App\Model\User;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;
use PhpOffice\PhpSpreadsheet\IOFactory;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class UserController extends AppBaseController
{

    /**
     * 后台--用户列表
     * @return object
     */
    #[RequestMapping(path:'userList',methods: 'get')]
    public function userList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 10);
            $offset = ($page - 1) * $limit;

            $where = [];
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }

            //用户筛选
            $auth_name = $this->request->input('auth_name', null);
            if($auth_name) $where[] = ['auth_name','like','%'.$auth_name.'%'];

            //工号筛选
            $auth_key = $this->request->input('auth_key', null);
            if($auth_key) $where[] = ['auth_key','like','%'.$auth_key.'%'];


            $listModel = User::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])
                ->selectRaw('id,party_id,user_type,nickname,avatar,auth_name,auth_key,auth_time,department,political_birthday,status')
                ->where($where);

            //认证筛选
            $auth_status = $this->request->input('auth_status', null);
            if($auth_status==1){
                $listModel->whereNotNull('auth_time');
            }else if($auth_status==2){
                $listModel->whereNull('auth_time');
            }

            $list = $listModel->orderByDesc('id')->offset($offset)->limit($limit)->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = User::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 后台--用户详情
     * @param int $uid
     * @return object
     */
    #[RequestMapping(path:'userInfo/{uid}',methods: 'get')]
    public function userInfo(int $uid): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = User::with(['party'=>function($query){
                    $query->selectRaw('id,name')->first();
                }])->where('id',$uid)
                ->selectRaw('id,nickname,avatar,auth_name,auth_key,party_id,user_type,integral,department,political_birthday')
                ->first();
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--用户新增|编辑
     * @param int|null $uid
     * @return object
     */
    #[RequestMapping(path: 'userInfoEdit[/{uid}]',methods: 'post,get')]
    public function userInfoEdit(int|null $uid): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['auth_name'] = 'ceshissssss';
//                $data['auth_key'] = '1111';
//                $data['user_type'] = 1;
//                $data['party_id'] = 1;
//                $data['department'] = '技术部';
//                $data['political_birthday']='2024-10-01';
//                $data['status'] = 1;
//            }
            //虚拟数据

            if( !isset($data['auth_name']) || $data['auth_name']==null
                || !isset($data['auth_key']) || $data['auth_key']==null
                || !isset($data['user_type']) || !in_array($data['user_type'],[1,2,8,10])
                || !isset($data['party_id']) || !is_numeric($data['party_id'])
                || !isset($data['department']) || $data['department']==null
                || !isset($data['political_birthday']) || $data['political_birthday']==null
            ) return $this->reMsg->re(10007);

            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            $party_id = $data['party_id'];
            if($uid){
                //编辑
                $info = User::where('id',$uid)->first();
                if(empty($info)) return $this->reMsg->re(10008);
                $info->auth_name = $data['auth_name'];
                $info->user_type = $data['user_type'];
                $info->department = $data['department'];
                $info->political_birthday = $data['political_birthday'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                //查询是否有重复工号
                $hasUser = User::where('auth_key' ,$data['auth_key'])->first();
                if($hasUser) return $this->reMsg->re(0,'该工号已存在，请换一个！');
                //新建
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertId = User::create($data);
                if($insertId){
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--用户切换状态
     * @param int $uid
     * @return object
     */
    #[RequestMapping(path:'userStatusChange/{uid}',methods: 'get')]
    public function userStatusChange(int $uid): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            //判断信息
            $info = User::where('id',$uid)->selectRaw('id,party_id,user_type,nickname,avatar,auth_name,auth_key,auth_time,status')->first();
            if(empty($info)) return $this->reMsg->re(10008);

            if($info->status==1){
                $info->status=0;
            }else{
                $info->status=1;
            }
            $info->save();

            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 后台--用户查询
     * @return object
     */
    #[RequestMapping(path:'userSearch',methods: 'get')]
    public function userSearch(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $name = $this->request->input('name',null);
            if($name==null) return $this->reMsg->re(10007);
            $where[] = ['auth_name','like','%'.$name.'%'];
            $where['status'] = 1;
            $list = User::with(['party'=>function($query){
                    $query->selectRaw('id,name')->first();
                }])->where($where)
                ->whereNotNull('auth_time')
                ->selectRaw('id,nickname,avatar,auth_name,party_id,user_type')
                ->get();
            $total=0;
            $next=0;
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 部门列表
     * @return object
     */
    #[RequestMapping(path:'departmentList',methods: 'get')]
    public function departmentList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $where['status'] = 1;
            $list = Department::where($where)
                ->orderByDesc('id')
                ->get();
            $next = 0;
            return $this->reMsg->re(1,'success',['list'=>$list,'next'=>$next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--活动答题题目导入
     * @return object
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    #[RequestMapping(path: "userImport", methods: "post")]
    public function userImport () :object
    {
        //验证管理员信息
        $checkInfo = $this->checkAdmin();
        if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
        $_admin = $checkInfo['data'];

        //获取文件
        $file = $this->request->file('file');
        if ($file == null)  return $this->reMsg->re(10007);
        $extension = $file->getExtension();
        if (!in_array($extension, ['xls', 'xlsx'])) {
            return $this->reMsg->re(0,'参数异常');
        }

        //判断权限
        if($_admin->level!=1) return $this->reMsg->re(0,'不可操作其他管理员数据');

        //执行导入
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($file->getPath() . '/' . $file->getFilename());
        $sheet = $spreadsheet->getSheet(0);
        $count_row = $sheet->getHighestRow();
        $count_column = $sheet->getHighestColumn();

        if ($count_row == 0)  return $this->reMsg->re(0,'导入数据为空');
        if($count_column != 'G') return $this->reMsg->re(0,'导入列异常');

        //获取党支部
        $partyList = Party::where('status',1)->selectRaw('id,name')->get();
        if($partyList->isEmpty()) return $this->reMsg->re(0,'党支部不可为空');
        $partyArr = [];
        foreach ($partyList as $key=>$value){
            $partyArr[$key] = $value->name;
        }

        //获取用户部门
        $departmentArr = Department::where('status',1)->pluck('name')->toArray();
        if(empty($departmentArr)) return $this->reMsg->re(0,'部门不可为空');

        //获取所有用户数据-工号
        $userKeyArr = User::pluck('auth_key')->toArray();

        try {
            Db::beginTransaction();

            for ($row = 2; $row <= $count_row; $row++){
                $_auth_name = $sheet->getCell('A' . $row)->getValue();
                if ($_auth_name == null) {
                    Db::rollBack();
                    return $this->reMsg->re(0, '第' . $row . '行数据异常，姓名为空错误');
                }

                $_auth_key = $sheet->getCell('B' . $row)->getValue();
                if ($_auth_key == null) {
                    Db::rollBack();
                    return $this->reMsg->re(0, '第' . $row . '行数据异常，工号为空错误');
                }
                if(in_array($_auth_key,$userKeyArr)){
                    Db::rollBack();
                    return $this->reMsg->re(0, '第' . $row . '行数据异常，工号不可重复错误');
                }
                //向数组将入新工号
                array_push($userKeyArr,$_auth_key);


                $_party_name = $sheet->getCell('C' . $row)->getValue();
                if (!in_array($_party_name, $partyArr)) {
                    Db::rollBack();
                    return $this->reMsg->re(0, '第' . $row . '行数据异常，未知党支部错误');
                }
                $_party_id = null;
                foreach ($partyList as $pKey=>$pValue){
                    if($_party_name==$pValue->name){
                        $_party_id = $pValue->id;
                        break;
                    }
                }

                $_department = $sheet->getCell('D' . $row)->getValue();
                if (!in_array($_department,$departmentArr)) {
                    Db::rollBack();
                    return $this->reMsg->re(0, '第' . $row . '行数据异常，未知部门错误');
                }


                $_user_type_tip = $sheet->getCell('E' . $row)->getValue();
                if (!in_array($_user_type_tip, ['群众','党员','通讯员','支部委员','支部书记','党委委员'])) {
                    Db::rollBack();
                    return $this->reMsg->re(0, '第' . $row . '行数据异常，未知用户身份错误');
                }

                if($_user_type_tip=='群众'){
                    $_user_type = 1;
                }else if($_user_type_tip=='党员'){
                    $_user_type = 2;
                }else if($_user_type_tip=='通讯员'){
                    $_user_type = 7;
                }else if($_user_type_tip=='支部委员'){
                    $_user_type = 8;
                }else if($_user_type_tip=='支部书记'){
                    $_user_type = 9;
                }else if($_user_type_tip=='党委委员'){
                    $_user_type = 10;
                }else{
                    $_user_type = 1;
                }


                $_political_birthday = $sheet->getCell('F' . $row)->getValue();
                if($_political_birthday){
                    $_political_birthday_date = strtotime($_political_birthday);
                    if ($_political_birthday_date == false) {
                        Db::rollBack();
                        return $this->reMsg->re(0, '第' . $row . '行数据异常，政治生日格式错误');
                    }
                }

                //实例化题目
                $userData['auth_name'] = $_auth_name;
                $userData['auth_key'] = $_auth_key;
                $userData['party_id'] = $_party_id;
                $userData['user_type'] = $_user_type;
                $userData['department'] = $_department;
                $userData['political_birthday'] = $_political_birthday;
                $userData['admin_id'] = $_admin->id;
                User::create($userData);
            }
            Db::commit();
            return $this->reMsg->re(1);
        } catch (\Exception $exception) {
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }




}